package com.an.spring.beanlife;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class BeanLifeCycle {

    private static void LifeCycleInBeanFactory(){
        //装载配置文件并启动容器
        Resource resource = new ClassPathResource("beanconfig.xml");
        BeanFactory bf = new DefaultListableBeanFactory();

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) bf);
        reader.loadBeanDefinitions(resource);

        //想容器中注册MyBeanPostProcessor后处理器
        ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyBeanPostProcessor());

        //向容器中注册后处理器
        ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());

        //第一次从容器中获取car，将触发容器实例化该bean，这将引发BEan生命周期方法调用
        Car car1 = (Car) bf.getBean("car");
        System.out.println(car1.introduce());
        car1.setColor("红色");
        System.out.println(car1.introduce());

        System.out.println("***************---------***************");
        //第二次会获取car，直接从缓存中获取
        Car car2 = (Car) bf.getBean("car");

        //查看是否默认为单例
        System.out.println("car1 == car2:" + (car1 == car2));
        System.out.println(car2.introduce());

        //gua关闭容器
        ((DefaultListableBeanFactory)bf).destroySingletons();

    }

    /*public static void main(String[] args){
        LifeCycleInBeanFactory();
    }*/
}
